import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:signature/signature.dart';
import 'package:top_foundation/utils/theme/theme.dart';
import 'package:whale/helper/utils/permisson.dart';
import 'package:whale/helper/utils/util.dart';

import '../index.dart';

class SignBoard extends StatefulWidget {
  const SignBoard({super.key, this.width, this.height = 200});
  final double? width;
  final double height;
  @override
  State<SignBoard> createState() => _SignBoardState();
}

class _SignBoardState extends State<SignBoard> {
  final List<Point> _cancelPoints = [];

  // Initialise a controller. It will contains signature points, stroke width and pen color.
// It will allow you to interact with the widget
  final SignatureController _controller = SignatureController(
    penStrokeWidth: 3,
    penColor: Colors.red,
    exportBackgroundColor: Colors.blue,
  );

  Widget _action(String text, VoidCallback onTap) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: Container(
          height: 36.r,
          alignment: Alignment.center,
          child: Text(
            text,
            style: TextStyle(color: Colors.white, fontSize: 15.sp),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Signature(
          controller: _controller,
          width: widget.width,
          height: widget.height,
          backgroundColor: Colors.lightBlueAccent,
        ),
        Container(
          color: Colors.black,
          child: Row(
            children: [
              _action('清除', _clear),
              _action('上一步', _last),
              _action('下一步', _next),
              _action('完成', _export)
            ],
          ),
        )
      ],
    );
  }

  void _last() {
    _controller.undo();
  }

  void _next() {
    _controller.redo();
  }

  void _clear() {
    _controller.clear();
  }

  void _export() async {
    if (_controller.isNotEmpty) {
      final data = await _controller.toPngBytes(
          width: (widget.width ?? 1.sw).floor() * 5,
          height: (widget.height * 5).floor());
      if (data != null) {
        await ImageGallerySaver.saveImage(data);
        Hud.toast('已经保存到相册');
      }
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
